from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth import authenticate, login  # 内置用户认证和管理应用中引入的两个方法
from .forms import LoginForm, RegistrationForm, UserProfileForm

# Create your views here.

def user_login(request):
    """ 用户登录验证视图 """
    if request.method == 'POST':
        login_form = LoginForm(request.POST)  # request.POST得到提交表单数据，是一个类字典对象
        if login_form.is_valid():  # 验证表单信息
            cd = login_form.cleaned_data  # 以字典的形式返回实例的具体数据，即经过校验之后的属性及其值
            user = authenticate(username=cd['username'], password=cd['password']) # 1
            if user:
                login(request, user)  # 以1所得的user实例对象作为参数，实现用户登录
                return HttpResponse('Welcome You. You have been authenticated successfully')
            else:
                return HttpResponse('Invalid login')
    if request.method == 'GET':
        login_form = LoginForm()   # 第一次向server发出含有表单页面的请求，然后反馈前端页面，等待用户输入
        return render(request, 'account/login.html', {'form': login_form})

def register(request):
    """ 用户注册视图 """
    if request.method == "POST":
        user_form = RegistrationForm(request.POST)
        userprofile_form = UserProfileForm(request.POST)
        if user_form.is_valid() * userprofile_form.is_valid():
            new_user = user_form.save(commit=False)  # 将表单数据保存到数据库，并生成数据对象;commit=False 仅仅生成数据对象
            new_user.set_password(user_form.cleaned_data['password'])
            new_user.save()
            new_profile = userprofile_form.save(commit=False)
            new_profile.user = new_user
            new_profile.save()
            return HttpResponse("successfully")
        else:
            return HttpResponse("sorry,your can't register.")
    else:
        user_form = RegistrationForm()
        userprofile_form = UserProfileForm()
        connext = {"form": user_form, "profile": userprofile_form}
        return render(request, "account/rigister.html", connext)